<template>
  <div class="content text-center">
    <div class="logo">
      会员管理系统
    </div>
    <div class="search-line">
      <input v-model.trim="serchValue" class="search-input" type="text" placeholder="请输入手机号" />
      <button class="search-btn" @click="search">搜索</button>
    </div>
    <DetaiDialog :dialogVisible.sync="dialogVisible" :detail="memberDetail" @submit="submit" />
  </div>
</template>
<script lang="ts">
import { Component, Provide, Watch, Vue } from 'vue-property-decorator'
import DetaiDialog from '@/components/DetailDialog.vue'
import { message } from '@/utils/components'
import * as api from '@/api'

/**
 * @Component 注解
 *    包含components属性，将组件SearchLine传递传递到父类的Vue的属性中
 */

@Component({
  components: {
    DetaiDialog,
  },
})
export default class List extends Vue {
  @Provide() serchValue: any = ''
  @Provide() memberDetail: any = {
    name: '',
    phone: '',
    amount: 0,
    type: 2,
    number: '',
  }
  @Provide() dialogVisible: boolean = false

  @Watch('dialogVisible')
  watchDialogHide(val: boolean) {
    if (!val) {
      this.memberDetail = {
        name: '',
        phone: '',
        amount: 0,
        type: 2,
        number: '',
      }
      this.serchValue = ''
    }
  }

  search() {
    let phoneReg = /^[1][0-9]{10}$/
    if (!phoneReg.test(this.serchValue)) {
      message('请输入正确的手机号', 'err')
      return
    } else {
      api.getList({ phone: this.serchValue }).then((res) => {
        if (res.data && res.data[0]) {
          let item = res.data[0]
          this.dialogVisible = true
          this.memberDetail = {
            phone: item.phone,
            name: item.name,
            balance: item.amount,
            amount: '',
            direction: 2,
          }
        } else {
          message('找不到该会员，请检查手机号是否正确', 'err')
        }
      })
    }
  }

  submit() {
    let numberReg = /^[0-9]+(\.[0-9]*)?$/
    if (!numberReg.test(this.memberDetail.amount)) {
      message('请输入正确的金额', 'err')
      return
    }

    api.updateItem(this.memberDetail).then((res) => {
      message(this.memberDetail.direction === 1 ? '充值成功' : '扣款成功')
      this.search()
    })
  }
}
</script>
<style lang="scss" scoped>
.logo {
  padding: 80px;
  color: #000;
  font-size: 36px;
  letter-spacing: 8px;
}

.search-input {
  width: 400px;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.search-btn {
  border-left: none;
  border-radius: 0 4px 4px 0;
}
</style>
